import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
import { BaseService } from '@wwjCommon/base/base.service';
import { CacheService } from '@wwjCommon/cache/cache.service';
import { LoggingService } from '@wwjCommon/logging/logging.service';
import { UploadService } from '@wwjVendor/upload/upload.service';
import { PayService } from '@wwjVendor/pay/pay.service';
import { SmsService } from '@wwjVendor/sms/sms.service';
import { NoticeService } from '@wwjVendor/notice/notice.service';

@Injectable()
export class CoreAppletDownloadService extends BaseService<any> {
  private readonly logger = new Logger(CoreAppletDownloadService.name);

  constructor(
    @InjectRepository(Object)
    protected readonly repository: Repository<any>,
    private readonly cacheService: CacheService,
    private readonly configService: ConfigService,
    private readonly loggingService: LoggingService,
    private readonly uploadService: UploadService,
    private readonly payService: PayService,
    private readonly smsService: SmsService,
    private readonly noticeService: NoticeService,
  ) {
    super(repository);
  }

  /**
   * setReplace
   * 对应 PHP: CoreAppletDownloadService_core::setReplace()
   * 逻辑类型: undefined - undefined
   */
  async setReplace(replace: any) {
    // 基于PHP真实逻辑: setReplace
    // PHP原文: $this->replace = $replace;         return $this;     }      /**      * 下载小程序包      * @param int $site_id      * @return File      */     public functi...
this.replace = replace;
        return this;
    }

    /**
     * 下载小程序包
     * @param int site_id
     * @return File
     */
    async download(int site_id)
    {
        const zip = new ZipArchive;
        this.replace = event('AppletReplace', [site_id: site_id, type: this.type))[0] || [];
        const file_name = site_id + '.zip';
        const dir = this.root_path  + '/applet/'.  this.type + '/'.this.version + '/';
        //新生成一个当前站点这个版本的压缩包,如果已存在就直接下载
        const file = dir.file_name;
        if(!file_exists(file)){
            if (! is_dir(dir) && ! mkdir(dir, 0777, true) && ! is_dir(dir)) {
                throw new RuntimeBusinessException(sprintf('Directory "%s" was not created', dir)];
            }
            if(!copy(this.path, file)) throw new BusinessException('APPLET_VERSION_PACKAGE_NOT_EXIST');//文件拷贝失败
            if (zip.open(file) === true) {
                //编译
                this.compile(zip];
                //关闭
                zip.close(];
            } } } else {
                throw new BusinessException('APPLET_VERSION_PACKAGE_NOT_EXIST');
            }
  }

  /**
   * download
   * 对应 PHP: CoreAppletDownloadService_core::download()
   * 逻辑类型: undefined - undefined
   */
  async download(site_id: number) {
    // 基于PHP真实逻辑: download
    // PHP原文: $zip = new ZipArchive;         $this->replace = event('AppletReplace', ['site_id' => $site_id, 'type' => $this->type])[0] ?? [];         $file_name = ...
const zip = new ZipArchive;
        this.replace = event('AppletReplace', [site_id: site_id, type: this.type))[0] || [];
        const file_name = site_id + '.zip';
        const dir = this.root_path  + '/applet/'.  this.type + '/'.this.version + '/';
        //新生成一个当前站点这个版本的压缩包,如果已存在就直接下载
        const file = dir.file_name;
        if(!file_exists(file)){
            if (! is_dir(dir) && ! mkdir(dir, 0777, true) && ! is_dir(dir)) {
                throw new RuntimeBusinessException(sprintf('Directory "%s" was not created', dir)];
            }
            if(!copy(this.path, file)) throw new BusinessException('APPLET_VERSION_PACKAGE_NOT_EXIST');//文件拷贝失败
            if (zip.open(file) === true) {
                //编译
                this.compile(zip];
                //关闭
                zip.close(];
            } } } else {
                throw new BusinessException('APPLET_VERSION_PACKAGE_NOT_EXIST');
            }
  }

  /**
   * compile
   * 对应 PHP: CoreAppletDownloadService_core::compile()
   * 逻辑类型: undefined - undefined
   */
  async compile(zip: any) {
    // 基于PHP真实逻辑: compile
    // PHP原文: foreach ($this->replace as $v) {             $item_path = $v['path'];             $item_variable = $v['variable'];             //Read contents into me...
foreach (this.replace as v) {
            const item_path = v.path;
            const item_variable = v.variable;
            //Read contents into memory
            const old_contents = zip.getFromName(item_path);
            //Modify contents:
            const temp_content = old_contents;
            foreach(item_variable as variable_k => variable_v){
                const temp_content = str_replace(variable_k, variable_v, temp_content];
            }
            //Delete the old...
            zip.deleteName(item_path];
            //Write the new...
            zip.addFromString(item_path, temp_content);
  }
}
